using AutoMapper;
using B.S.XZYData.Api.Read.Application.Command.WorkOrder;
using B.S.XZYData.Api.Read.Dto.WorkOrder;
using B.S.XZYData.Domain.LJC;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.XZYData.Api.Read.Application.Handler.WorkOrder
{
    /// <summary>
    /// 获取工单详情处理器
    /// </summary>
    public class GetWorkOrderDetailHandler : IRequestHandler<GetWorkOrderDetailCommand, ApiResult<WorkOrderDetailDto>>
    {
        private readonly IBaseRepository<WorkOrderModel> _workOrderRepo;
        private readonly IBaseRepository<WorkOrderProcessModel> _workOrderProcessRepo;
        private readonly IBaseRepository<WorkOrderAssignModel> _workOrderAssignRepo;
        private readonly IMapper _mapper;

        public GetWorkOrderDetailHandler(
            IBaseRepository<WorkOrderModel> workOrderRepo,
            IBaseRepository<WorkOrderProcessModel> workOrderProcessRepo,
            IBaseRepository<WorkOrderAssignModel> workOrderAssignRepo,
            IMapper mapper)
        {
            _workOrderRepo = workOrderRepo;
            _workOrderProcessRepo = workOrderProcessRepo;
            _workOrderAssignRepo = workOrderAssignRepo;
            _mapper = mapper;
        }

        public async Task<ApiResult<WorkOrderDetailDto>> Handle(GetWorkOrderDetailCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<WorkOrderDetailDto>();

            try
            {
                // 获取工单信息
                var workOrder = _workOrderRepo.GetAll()
                    .Where(x => x.Id == request.WorkOrderId).ToList().FirstOrDefault();

                if (workOrder == null)
                {
                    res.Code = ApiEnum.Error;
                    res.Msg = "工单不存在";
                    return res;
                }

                // 映射工单基本信息
                var workOrderDetailDto = _mapper.Map<WorkOrderDetailDto>(workOrder);

                // 获取工单工序列表
                var processes = _workOrderProcessRepo.GetAll()
                    .Where(x => x.WorkOrderId == request.WorkOrderId)
                    .OrderBy(x => x.Sequence)
                    .ToList();

                // 调试日志
                Console.WriteLine($"[Debug] 工单ID: {request.WorkOrderId}");
                Console.WriteLine($"[Debug] 查询到的工序数量: {processes.Count}");
                foreach (var process in processes)
                {
                    Console.WriteLine($"[Debug] 工序: {process.ProcessName}, 序号: {process.Sequence}");
                }

                // 映射工序信息
                var processDtos = _mapper.Map<List<WorkOrderProcessDto>>(processes);

                // 获取每个工序的分派信息
                foreach (var processDto in processDtos)
                {
                    var assigns = _workOrderAssignRepo.GetAll()
                        .Where(x => x.WorkOrderProcessId == processDto.Id)
                        .ToList();

                    processDto.Assigns = _mapper.Map<List<WorkOrderAssignDto>>(assigns);
                }

                workOrderDetailDto.Processes = processDtos;

                res.Data = workOrderDetailDto;
                res.Code = ApiEnum.Success;
                res.Msg = "获取工单详情成功";
            }
            catch (Exception ex)
            {
                res.Code = ApiEnum.Error;
                res.Msg = $"获取工单详情失败：{ex.Message}";
            }

            return res;
        }
    }
}
